//
//  HTHomeTableViewController.swift
//  mySinaBlog
// https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.006ndg5GEwpRuCea29479d2a0AQ1Hn
//  Created by whtapple on 3/21/16.
//  Copyright © 2016 whtapple. All rights reserved.
//

import UIKit
import SVPullToRefresh

// 重用字符串
let ReuseIdentifier = "ReuseIdentifier"
class HTHomeTableViewController: HTBaseViewController {
    //记录下两个 id
    var max_id: Int64 = 0
    //状态数据
    var statusData:[HTStatus]?{
        didSet{
            self.tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        if !HTUserAccountViewModel.sharedInstance.isLogin() == true {
            return
        }
        setUpBarButtonItem()
        setupTitle()
        prepareTableView()
    }
    //MARK: -准备 tableView
    private func prepareTableView(){
        //注册cell
        tableView.registerClass(HTHomeCell.self, forCellReuseIdentifier:ReuseIdentifier)
        //设置行高自适应
        tableView.rowHeight  = UITableViewAutomaticDimension
        //预设行高
        tableView.estimatedRowHeight = 200
        //去掉分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        //将下拉刷新控件加进来
        tableView.addpulldownRefreshHader { [weak self] () -> () in
            self?.loadNewData()
        }
        tableView.startRefreshing()
    }
    //MARK: -显示加载的数据动画
    private func showTipLabelAnimation(count: Int){
        tipLabel.text = count == 0 ? "没有加载新的微博数据" : "加载了\(count)条微博数据"
        UIView.animateWithDuration(defaultduration * 4, animations: { () -> Void in
            if self.max_id > 0{
                self.tipLabel.frame.origin.y = UIScreen.height - 110
            }else{
                 self.tipLabel.frame.origin.y = 44
            }
            Xprint(msg:"max_id = \(self.max_id)" )
            }) { (_) -> Void in
                UIView.animateWithDuration(defaultduration * 4, delay: defaultduration * 2, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    if self.max_id > 0{
                        self.tipLabel.frame.origin.y = UIScreen.height
                    }else{
                        self.tipLabel.frame.origin.y = -64
                    }
                    
                    }, completion: nil)
//                Xprint(msg:"max_id = \(self.max_id)" )
        }
    }
    ///下拉加载加载数据
    private func loadNewData(){
        let since_id = self.statusData?.first?.id ?? 0
        HTStatusViewModel.sharedInstance.loadStatusData(since_id, max_id: 0) { [weak self](model, error) -> () in
            self!.tableView.endRefreshing()
            if error != nil{
                print("状态数据加载出错\(error)")
            }
            let conunt = model?.count ?? 0
            self!.max_id = 0
            self!.tipLabel.frame.origin.y = -64
            self!.showTipLabelAnimation(conunt)
            if conunt == 0{
                Xprint(msg: "没有加载到数据")
                return
            }
            if since_id > 0{
                Xprint(msg: "下拉刷新count:\(conunt)")
                self!.statusData = model! + self!.statusData!
            }else{
                self!.statusData = model
            }
            Xprint(msg: "最终加载微博数：\(self!.statusData?.count)")
            //上拉加载数据
            self!.tableView.addInfiniteScrollingWithActionHandler { () -> Void in
                self!.loadMoreStatus()
            }

        }
    }
    //上拉加载数据
    private func loadMoreStatus(){
        let max_id = self.statusData?.last?.id ?? 0
        HTStatusViewModel.sharedInstance.loadStatusData(0, max_id: max_id) { (model, error) -> () in
           self.tableView.infiniteScrollingView.stopAnimating()
            if error != nil{
                print("状态数据加载出错\(error)")
            }
            let conunt = model?.count ?? 0
            self.max_id = max_id
            self.tipLabel.frame.origin.y = UIScreen.height
            self.showTipLabelAnimation(conunt)
            if conunt == 0{
                Xprint(msg: "没有加载到数据")
                return
            }
            self.statusData = self.statusData! + model!
            Xprint(msg: "上拉加载更多数据：\(model?.count)")
            Xprint(msg: "最终微博数据条数：\(self.statusData?.count)")
        }
    }
    //MARK: -设置左右的 button
    private func setUpBarButtonItem(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageString: "navigationbar_friendsearch", target: self, selector: "didClickedleftBarButton")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageString: "navigationbar_pop", target: self, selector: "didClickedrightBarButton")
    }
    //MARK: -设置 title
    private func setupTitle(){
        let title = HTUserAccountViewModel.sharedInstance.userAccount!.screen_name
        let titleBtn = HTHomeTitleButtonView(title: title!, image: "navigationbar_arrow_down")
        titleBtn.addTarget(self, action: "didClickTitleBtn:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleBtn
    }
    //左边点击方法，必须不是私有的，因为需要被系统调用，系统不算内部方法
    @objc private func didClickedleftBarButton(){
        print(__FUNCTION__)
    }
    //右边点击方法，必须不是私有的，因为需要被系统调用，系统不算内部方法
    @objc private func didClickedrightBarButton(){
        print(__FUNCTION__)
    }
    //title点击方法，必须不是私有的，因为需要被系统调用，系统不算内部方法
    @objc private func didClickTitleBtn(btn: HTHomeTitleButtonView){
        btn.selected = !btn.selected
        UIView.animateWithDuration(anmateTime) { () -> Void in
            btn.imageView?.transform = btn.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) :CGAffineTransformIdentity
        }
        if btn.selected {
            //创建一个 VC
            let popoverVC = HTPopverViewController()
            //modal方式
            popoverVC.modalPresentationStyle = UIModalPresentationStyle.Popover
            //设置代理
            popoverVC.popoverPresentationController?.delegate = self
            //这两步确定了指针的位置
            popoverVC.popoverPresentationController?.sourceView = navigationItem.titleView
            popoverVC.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
            popoverVC.popoverPresentationController!.permittedArrowDirections = UIPopoverArrowDirection.Right
            //设置 pop出了的 view大小
            presentViewController(popoverVC, animated: true, completion: nil)
            popoverVC.preferredContentSize = CGSizeMake(200, 250)
        }
    }
    //懒加载数据
    private lazy var tipLabel: UILabel = {
        let tlabel = UILabel()
        tlabel.backgroundColor = UIColor.orangeColor()
        tlabel.font = UIFont.systemFontOfSize(18)
        tlabel.textAlignment = NSTextAlignment.Center
        tlabel.textColor = UIColor.whiteColor()
        tlabel.frame = CGRect(x: 0, y: -64, width: UIScreen.width, height: 44)
        self.navigationController?.navigationBar.insertSubview(tlabel, atIndex: 0)
        return tlabel
    }()
}
//MARK: tableView代理扩展

extension HTHomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 20
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier, forIndexPath: indexPath) as? HTHomeCell
        cell?.status = statusData?[indexPath.item]
        
        return cell!
    }
    //取消 cell 的选中
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
}
//MARK: popover代理扩展
extension HTHomeTableViewController: UIPopoverPresentationControllerDelegate{
    //使 pop出来的 vc不要去适应屏幕否则总是显示全票
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    //在关闭时，调用didClickTitleBtn，使btn也被点击一下，否则 btn还是属于被选中状态
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        let btn = navigationItem.titleView as! HTHomeTitleButtonView
        didClickTitleBtn(btn)
        return true
    }
}
